package com.example.zhinongbao.database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.zhinongbao.entity.Cart;
import com.example.zhinongbao.entity.Goods;
import com.example.zhinongbao.entity.Photo;
import com.example.zhinongbao.entity.UserInfo;

import java.util.ArrayList;
import java.util.List;

public class UserInfoDao {
    private DBHelper dbHelper ;
    private CartDBHelper cartDBHelper ;
    public UserInfoDao(Context context){
        dbHelper =new DBHelper(context);
        cartDBHelper = new CartDBHelper(context);
    }

//    @SuppressLint("Range")
//    public UserInfo getUserByName(String username){
//        SQLiteDatabase  db= dbHelper.getReadableDatabase();
//
//        String[] selectionArgs = {username};
//        UserInfo userInfo = null;
//        Cursor cursorr = db.query(TABLE_NAME_USER_TABLE,)
//        if (cursorr.moveToFirst()) {
//            int user_id = cursorr.getInt(cursorr.getColumnIndex("user_id"));
//            String password = cursorr.getString(cursorr.getColumnIndex("password"));
//            String nickname = cursorr.getString(cursorr.getColumnIndex("nickname"));
//            String phone = cursorr.getString(cursorr.getColumnIndex("phone"));
//            int age = cursorr.getInt(cursorr.getColumnIndex("age"));
//            String address = cursorr.getString(cursorr.getColumnIndex("address"));
//            String paypassword =cursorr.getString(cursorr.getColumnIndex("paypassword"));
//            String concern =cursorr.getString(cursorr.getColumnIndex("concern"));
//            userInfo = new UserInfo(user_id, username, password, nickname, age, address, phone,paypassword,concern);
//        }
//        cursorr.close();
//        db.close();
//        return userInfo;
//    }
@SuppressLint("Range")
public UserInfo getUserByName(String username) {
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    String[] columns = {"user_id", "password", "nickname", "phone", "age", "address", "paypassword", "concern"};
    String selection = "username = ?";
    String[] selectionArgs = {username};

    Cursor cursor = null;
    UserInfo userInfo = null;

    try {
        cursor = db.query("user_table", columns, selection, selectionArgs, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            String user_id = cursor.getString(cursor.getColumnIndex("user_id"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            String nickname = cursor.getString(cursor.getColumnIndex("nickname"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            int age = cursor.getInt(cursor.getColumnIndex("age"));
            String address = cursor.getString(cursor.getColumnIndex("address"));
            String paypassword = cursor.getString(cursor.getColumnIndex("paypassword"));
            String concern = cursor.getString(cursor.getColumnIndex("concern"));

            userInfo = new UserInfo(user_id, password, nickname, phone, age, address, paypassword, concern);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
        db.close();
    }

    return userInfo;
}
    //修改密码
    public void updatePasswordByUserName(String username, String newPassword) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("password", newPassword);
        String selection = "username = ?";
        // 注意这里使用字符串数组传递参数，确保username变量是安全的
        db.update("user_table", values, selection, new String[]{username});
    }
//
    // 修改支付密码
    public void updatePayPasswordByName(String username, String newPayPassword) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("paypassword", newPayPassword);
        String selection = "username = ?";
        // 注意这里使用字符串数组传递参数，确保username变量是安全的
        db.update("user_table", values, selection, new String[]{username});
    }

    //修改年龄
    public void updateAgeByUserName(String username, String newAge) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("age", newAge);
        String selection = "username = ?";
        // 注意这里使用字符串数组传递参数，确保username变量是安全的
        db.update("user_table", values, selection, new String[]{username});
    }

//    //修改姓名
//    public void updateIdByUserName(String username, String newID) {
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        ContentValues values = new ContentValues();
//        values.put("user_id", newID);
//        String selection = username + " = ? ";
//        db.update("user_table", values, selection, new String[]{username});
//    }
    //修改id
public void updateIdByUserName(String username, String newID) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("user_id", newID);
    String selection = "username = ?";
    // 注意这里使用字符串数组传递参数，确保username变量是安全的
    db.update("user_table", values, selection, new String[]{username});
}
    //修改地址
    public void updateAddressByUserName(String username, String newAddress) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("address", newAddress);
        String selection = "username = ?";
        // 注意这里使用字符串数组传递参数，确保username变量是安全的
        db.update("user_table", values, selection, new String[]{username});
    }
//
//    public void updateConcernByUserId(String user_id, String newAvatar) {
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        ContentValues values = new ContentValues();
//        values.put("concern", newAvatar);
//        String selection = user_id + " = ?";
//        db.update("user_table", values, selection, new String[]{user_id});
//    }
//
    public void updatePhoneByUserName(String username, String newphone) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("phone", newphone);
        String selection = "username = ?";
        // 注意这里使用字符串数组传递参数，确保username变量是安全的
        db.update("user_table", values, selection, new String[]{username});
    }

    @SuppressLint("Range")
    public List<Cart> getCartByPhone(){
        SQLiteDatabase db = null ;
        Cursor cursor = null ;
        List<Cart> cartList = new ArrayList<>();
        try {
            db = cartDBHelper.getReadableDatabase();
            String query = "SELECT * FROM " + CartDBHelper.TABLE_CART + " WHERE " +

                    CartDBHelper.CART_ID + "  " ;
            cursor = db.rawQuery(query , new String[]{});
            while (cursor.moveToNext()){
                Cart cart = new Cart();
                cart.setId(cursor.getInt(cursor.getColumnIndex(CartDBHelper.CART_ID)));
                cart.setGoodsId(cursor.getInt(cursor.getColumnIndex(CartDBHelper.CART_GOODS_ID)));


                cartList.add(cart);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null){
                cursor.close();
            }
            if (db != null){
                db.close();
            }
        }
        return cartList ;
    }
    @SuppressLint("Range")
    public Cart getCartById(int id){
        SQLiteDatabase db = cartDBHelper.getReadableDatabase() ;
        Cursor cursor = db.query(CartDBHelper.TABLE_CART , new String[]{
                        CartDBHelper.CART_ID , CartDBHelper.CART_GOODS_ID , CartDBHelper.CART_GOODS_NUM , CartDBHelper.CART_USER},
                CartDBHelper.CART_ID + " =? " , new String[]{String.valueOf(id)} ,
                null , null, null,null
        );
        Cart cart = null ;
        if (cursor != null && cursor.moveToFirst()){
            cart = new Cart(
                    cursor.getInt(cursor.getColumnIndex(CartDBHelper.CART_ID)),
                    cursor.getInt(cursor.getColumnIndex(CartDBHelper.CART_GOODS_ID)),
                    cursor.getInt(cursor.getColumnIndex(CartDBHelper.CART_GOODS_NUM)),
                    cursor.getString(cursor.getColumnIndex(CartDBHelper.CART_USER))
            );
            cursor.close();
        }
        return cart ;
    }

    //通过Id查询商品
    @SuppressLint("Range")
    public Goods getGoodsById(int goodsId){
//        SQLiteDatabase db = dbHelper.getReadableDatabase() ;
//        Cursor cursor = db.query("goods",new String[]{"_id",},"_id = ?",new String[]{"_id"},null,null,null,null);
//        Goods goods = null ;
//        if (cursor!= null && cursor.moveToFirst()){
//            goods = new Goods(
//                    cursor.getInt(cursor.getColumnIndex("_id")),
//                    cursor.getString(cursor.getColumnIndex("goods_message")),
//                    cursor.getString(cursor.getColumnIndex("goods_name")),
//                    cursor.getDouble(cursor.getColumnIndex("goods_price")),
//                    cursor.getString(cursor.getColumnIndex("goods_unit")),
//                    cursor.getInt(cursor.getColumnIndex("goods_browse"))
//
//            );
//            cursor.close();
//        }
//        return goods ;
// 假设 DBHelper 类已经实现了 SQLiteOpenHelper 并提供了 getReadableDatabase 方法
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        Goods goods = null;

        try {
            // 使用商品ID查询商品信息
            cursor = db.query("goods", null, "_id = ?", new String[]{String.valueOf(goodsId)}, null, null, null);

            if (cursor.moveToFirst()) {
                // 假设Goods表的字段与Goods实体类的属性一一对应
                goods = new Goods();
                goods.setId(cursor.getInt(cursor.getColumnIndex("_id")));
                goods.setName(cursor.getString(cursor.getColumnIndex("goods_name")));
                goods.setPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
                // 如果需要设置商品图片
                // goods.setImg(cursor.getBlob(cursor.getColumnIndex("img")));
            }

            // 由于没有 Context 对象，我们不能使用 ContentResolver 来查询 photo 表
            // 你需要使用相同的 SQLiteDatabase 实例来查询 photo 表
            // 假设 photo 表与 goods 表有关联，并且 photo 表中有 goods_id 字段
            Cursor photoCursor = db.query("photo", null, "goods_id = ?", new String[]{String.valueOf(goodsId)}, null, null, null);

            try {
                if (photoCursor != null && photoCursor.moveToFirst()) {
                    do {
                        Photo photo = new Photo();
                        photo.setId(photoCursor.getInt(photoCursor.getColumnIndex("_id")));
                        photo.setData(photoCursor.getBlob(photoCursor.getColumnIndex("image")));
                        goods.addPhoto(photo); // 确保 Goods 类有 addPhoto 方法
                    } while (photoCursor.moveToNext());
                }
            } finally {
                if (photoCursor != null) {
                    photoCursor.close(); // 关闭 photoCursor 以避免资源泄露
                }
            }

            // 打印商品信息
            Log.d("queryGoodsById", "Goods info: " + goods.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close(); // 关闭 cursor
            }
            db.close(); // 关闭数据库
        }

        return goods;
    }

    public void deleteCartById(int id){
        SQLiteDatabase db = cartDBHelper.getWritableDatabase();
        db.delete(CartDBHelper.TABLE_CART , CartDBHelper.CART_ID + " = ?" ,
                new String[]{String.valueOf(id)});
    }

    public void updateCartNumById(int id , int num){
        SQLiteDatabase db = cartDBHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(CartDBHelper.CART_GOODS_NUM , num);
        String selection = CartDBHelper.CART_ID + " = ? " ;
        db.update(CartDBHelper.TABLE_CART , values , selection , new String[]{String.valueOf(id)});
    }





    //以下是关于购物车的操作方法
    //添加购物车
    public void addCart(int goodsId ){
        SQLiteDatabase db = cartDBHelper.getWritableDatabase() ;
        ContentValues values = new ContentValues();
        values.put(CartDBHelper.CART_GOODS_ID , goodsId);

        db.insert(CartDBHelper.TABLE_CART , null , values);
    }


































    }














